package net.zoneland.zrdp.system.service.impl;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import net.zoneland.zrdp.common.annotation.DataSource;
import net.zoneland.zrdp.common.constant.CacheConstants;
import net.zoneland.zrdp.common.constant.UserConstants;
import net.zoneland.zrdp.common.core.redis.RedisService;
import net.zoneland.zrdp.common.core.text.Convert;
import net.zoneland.zrdp.common.enums.DataSourceType;
import net.zoneland.zrdp.common.exception.ServiceException;
import net.zoneland.zrdp.system.domain.SysConfig;
import net.zoneland.zrdp.system.mapper.SysConfigMapper;
import net.zoneland.zrdp.system.service.ISysConfigService;

/**
 * 参数配置 服务层实现
 *
 * @author zonevue
 */
@Service
public class SysConfigServiceImpl implements ISysConfigService {
    @Resource
    private SysConfigMapper configMapper;

    @Resource
    private RedisService redisService;

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init()
    {
        loadingConfigCache();
    }

    /**
     * 查询参数配置信息
     *
     * @param configId 参数配置ID
     * @return 参数配置信息
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public SysConfig selectConfigById(final Long configId) {
        final SysConfig config = new SysConfig();
        config.setConfigId(configId);
        return configMapper.selectConfig(config);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public SysConfig selectConfigByConfigKey(final String configKey) {
        final SysConfig config = new SysConfig();
        config.setConfigKey(configKey);
        return configMapper.selectConfig(config);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(final String configKey) {
        final String configValue = Convert.toStr(redisService.getCacheString(getCacheKey(configKey)));
        if (StringUtils.isNotEmpty(configValue)) {
            return configValue;
        }
        final SysConfig config = new SysConfig();
        config.setConfigKey(configKey);
        final SysConfig retConfig = configMapper.selectConfig(config);
        if (!Objects.isNull(retConfig)) {
            redisService.setCacheString(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取验证码开关
     *
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaEnabled() {
        final String captchaEnabled = selectConfigByKey("sys.account.captchaEnabled");
        if (StringUtils.isEmpty(captchaEnabled)) {
            return true;
        }
        return Convert.toBool(captchaEnabled);
    }

    /**
     * 查询参数配置列表
     *
     * @param config 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public List<SysConfig> selectConfigList(final SysConfig config)
    {
        return configMapper.selectConfigList(config);
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int insertConfig(final SysConfig config) {
        final int row = configMapper.insertConfig(config);
        if (row > 0) {
            redisService.setCacheString(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int updateConfig(final SysConfig config) {
        final SysConfig temp = configMapper.selectConfigById(config.getConfigId());
        if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey())) {
            redisService.deleteObject(getCacheKey(temp.getConfigKey()));
        }

        final int row = configMapper.updateConfig(config);
        if (row > 0) {
            redisService.setCacheString(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 批量删除参数信息
     *
     * @param configIds 需要删除的参数ID
     */
    @Override
    public void deleteConfigByIds(final Long[] configIds) {
        for (final Long configId : configIds) {
            final SysConfig config = selectConfigById(configId);
            if (StringUtils.equals(UserConstants.YES, config.getConfigType())) {
                throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
            }
            configMapper.deleteConfigById(configId);
            redisService.deleteObject(getCacheKey(config.getConfigKey()));
        }
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache() {
        final List<SysConfig> configsList = configMapper.selectConfigList(new SysConfig());
        for (final SysConfig config : configsList) {
            redisService.setCacheString(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache() {
        final Collection<String> keys = redisService.keys(CacheConstants.SYS_CONFIG_KEY + "*");
        redisService.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public boolean checkConfigKeyUnique(final SysConfig config) {
        final long configId = Objects.isNull(config.getConfigId()) ? -1L : config.getConfigId();
        final SysConfig info = configMapper.selectOneByConfigKey(config.getConfigKey());
        return  Objects.isNull(info) || info.getConfigId() == configId;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(final String configKey) {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }
}
